<?php


if (get_magic_quotes_gpc()) {
    function amazon_stripslashes_deep($value)
    {
        $value = is_array($value) ?
                    array_map('stripslashes_deep', $value) :
                    stripslashes($value);

        return $value;
    }

    /*$_POST = array_map('stripslashes_deep', $_POST);
    $_GET = array_map('stripslashes_deep', $_GET);
    $_COOKIE = array_map('stripslashes_deep', $_COOKIE);
    $_REQUEST = array_map('stripslashes_deep', $_REQUEST);*/
}




function amazon_sanitize_title($title) {
	$title = strip_tags($title);
	// Preserve escaped octets.
	$title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
	// Remove percent signs that are not part of an octet.
	$title = str_replace('%', '', $title);
	// Restore octets.
	$title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);

	$title = strtolower($title);
	$title = preg_replace('/&.+?;/', '', $title); // kill entities
	$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
	$title = preg_replace('/\s+/', '-', $title);
	$title = preg_replace('|-+|', '-', $title);
	$title = trim($title, '-');

	$title = substr($title, 0, 50);
	$title = str_replace("--", "-", $title);
	$title = str_replace("--", "-", $title);
	return $title;
}

function guess_url() {
	$schema = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) == 'on' ) ? 'https://' : 'http://';
	$url = preg_replace('|/admin/.*|i', '', $schema . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
	return $url;
}



function amazon_get_permalink($asin, $title) {
	$permalink = amazon_sanitize_title($title).'-'.$asin;
	$permalink = str_replace("--","-",$permalink);
	return $permalink;
}

function amazon_update_widget($type, $val) {
	global $db;

	$val = sqlite_escape_string($val);
	sqlite_exec($db, "UPDATE widget SET val='$val' WHERE type='$type'");
}

function amazon_get_widget($type) {
	global $db;
	$result = sqlite_query($db,"SELECT val FROM widget WHERE type='$type'");
	if( sqlite_num_rows($result) < 1 ) {
		sqlite_exec($db, "INSERT INTO widget(type, val) VALUES ('$type','')");

		return "";
	} else {
		$line = sqlite_fetch_array($result);
		return $line['val'];
	}
}

function my_encode($str) {
	$str = strip_tags($str);
	$str = str_replace("&","&amp;",$str);
	$str = str_replace('"',"&quot;",$str);
	$str = str_replace("'","&#039;",$str);
	return $str;
}

function item_get_price($item) {
	if( count($item->Offers->Offer) > 0 ) $price = $item->Offers->Offer->OfferListing->Price->FormattedPrice;
	if( !$price || $price == 'Too low to display') $price = $item->OfferSummary->LowestNewPrice->FormattedPrice;
	if( !$price || $price == 'Too low to display') $price = $item->ListedPrice->FormattedPrice;
	if( !$price || $price == 'Too low to display') $price = $item->VariationSummary->LowestPrice->FormattedPrice;
	if( !$price || $price == 'Too low to display') $price = "N/A";
	return $price;
}

function item_get_thumb($item, $maxwidth = 200) {
	$image = $item->MediumImage;
	return item_trim_image($image, $maxwidth);
}
function item_get_image($item, $maxwidth = 400) {
	$image = $item->LargeImage;	
	return item_trim_image($image, $maxwidth);
}

function item_trim_image($image, $maxwidth) {
	if(!$image) return null;
	$ratio = $image->Width / $maxwidth;
	if($ratio < 1) $ratio = 1;
	$image->Width = (int) ($image->Width / $ratio);
	$image->Height = (int) ($image->Height / $ratio);	
	return $image;
}

function amazon_request($str) {	
	global $amazon_zone, $amazon_api, $amazon_apix, $xConfig;
		
	/*$rest_param = 'Sort='.$xConfig["Sort"].'&Service=AWSECommerceService&AWSAccessKeyId='.$amazon_api.'&'.$str.
			'&Version=2009-01-06&Timestamp='.gmdate("Y-m-d\TH:i:s\Z");*/
	$rest_param = 'Service=AWSECommerceService&AWSAccessKeyId='.$amazon_api.'&'.$str.
			'&Version=2009-01-06&Timestamp='.gmdate("Y-m-d\TH:i:s\Z");
	$rest_param = str_replace(",","%2C",$rest_param);
	$rest_param = str_replace(":","%3A",$rest_param);
	
	$rest_param_arr = explode('&', $rest_param);
	sort($rest_param_arr);
	$rest_param = implode('&', $rest_param_arr);
	
	$rest_prepend = "GET\necs.amazonaws.".$amazon_zone."\n/onca/xml\n".$rest_param;
	$signature = base64_encode(hash_hmac("sha256", $rest_prepend, $amazon_apix, True));
	$signature = urlencode($signature);

	return "http://ecs.amazonaws.".$amazon_zone."/onca/xml?".$rest_param."&Signature=".$signature;
}


function amazon_help($arg) {
	echo "<a class=\"help\"><img src=\"".guess_url()."/images/help.png\" /><span class=\"inner\">".$arg."<span></a>";
}

function amazon_get_url($url) {
	
	if( strtolower(ini_get('allow_url_fopen')) == "on" ) {
		$data = file_get_contents($url);
	} else {
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //Set curl to return the data instead of printing it to the browser.
		curl_setopt($ch, CURLOPT_URL, $url);
		$data = curl_exec($ch);
		curl_close($ch);
		return $data;
	}
}


//#######################################edit by bird###########################################


//#################Product####################
function get_product($key) {
	global $db;
	
	$query_error="";
	$sql = "SELECT * FROM Product";
	$result = sqlite_query($db, $sql, SQLITE_ASSOC, $query_error);
	if($query_error)  sqlite_exec($db, "CREATE TABLE [Product] ([key] VARCHAR(50)  PRIMARY KEY NULL,[val] VARCHAR(255)  NULL);");
	
	$sql = "SELECT val FROM Product WHERE key='".$key."' ";
	//return $sql;
	$result = sqlite_query($db,$sql);
	if( sqlite_num_rows($result) < 1 ) {
		sqlite_exec($db, "INSERT INTO Product(key, val) VALUES ('$key','')");

		return "";
	} else {
		$line = sqlite_fetch_array($result);
		return $line['val'];
	}
}

function refresh_product() {
	global $product_path,$product_keyword,$product_description;
	$product_path = get_product('product_path');
	$product_keyword = get_product('product_keyword');
	$product_description = get_product('product_description');
}

function update_product($key, $val) {
	global $db;
	$result = sqlite_query($db, "SELECT val FROM Product WHERE key='$key'", SQLITE_ASSOC);
	$line = sqlite_fetch_array($result);
	if( $line ) {
		sqlite_exec($db, "UPDATE Product SET val='".$val."' WHERE key='".$key."'");
	} else {
		sqlite_exec($db, "INSERT INTO Product(val, key) VALUES('".$val."', '".$key."')");
	}
}
//#################Product####################

//#################Webmaster####################
function get_webmaster($key) {
	global $db;
	
	$query_error="";
	$sql = "SELECT * FROM Webmaster";
	$result = sqlite_query($db, $sql, SQLITE_ASSOC, $query_error);
	if($query_error)  sqlite_exec($db, "CREATE TABLE [Webmaster] ([key] VARCHAR(50)  PRIMARY KEY NULL,[val] VARCHAR(255)  NULL);");
	
	$sql = "SELECT val FROM Webmaster WHERE key='".$key."' ";
	//return $sql;
	$result = sqlite_query($db,$sql);
	if( sqlite_num_rows($result) < 1 ) {
		sqlite_exec($db, "INSERT INTO Webmaster(key, val) VALUES ('$key','')");

		return "";
	} else {
		$line = sqlite_fetch_array($result);
		return $line['val'];
	}
}

function refresh_webmaster() {
	global $meta_title,$meta_description,$meta_keyword,$meta_tracking,$meta_tracking_select,$meta_google,$meta_yahoo,$meta_bing;
	$meta_title = get_webmaster('meta_title');
	$meta_description = get_webmaster('meta_description');
	$meta_keyword = get_webmaster('meta_keyword');
	$meta_tracking = get_webmaster("meta_tracking");
	$meta_tracking_select = get_webmaster("meta_tracking_select");
	$meta_google = get_webmaster("meta_google");
	$meta_yahoo = get_webmaster("meta_yahoo");
	$meta_bing = get_webmaster("meta_bing");
}

function update_webmaster($key, $val) {
	global $db;
	$result = sqlite_query($db, "SELECT val FROM Webmaster WHERE key='$key'", SQLITE_ASSOC);
	$line = sqlite_fetch_array($result);
	if( $line ) {
		sqlite_exec($db, "UPDATE Webmaster SET val='".$val."' WHERE key='".$key."'");
	} else {
		sqlite_exec($db, "INSERT INTO Webmaster(val, key) VALUES('".$val."', '".$key."')");
	}
}
//#################Webmaster####################

//#################Page####################
function amazon_get_page($key) {
	global $db;
	
	$query_error="";
	$sql = "SELECT * FROM Page";
	$result = sqlite_query($db, $sql, SQLITE_ASSOC, $query_error);
	if($query_error)  sqlite_exec($db, "CREATE TABLE [Page] ([key] VARCHAR(50)  PRIMARY KEY NULL,[val] TEXT  NULL);");
	
	$sql = "SELECT val FROM Page WHERE key='".$key."' ";
	//return $sql;
	$result = sqlite_query($db,$sql);
	if( sqlite_num_rows($result) < 1 ) {
		sqlite_exec($db, "INSERT INTO Page(key, val) VALUES ('$key','')");

		return "";
	} else {
		$line = sqlite_fetch_array($result);
		return $line['val'];
	}
}

function amazon_refresh_page() {
	global $about_content,$contact_content,$privacy_content,$header_content_1,$header_content_2,$footer_content;
	$about_content = amazon_get_page('about_content');
	$contact_content = amazon_get_page('contact_content');
	$privacy_content = amazon_get_page('privacy_content');
	$header_content_1 = amazon_get_page('header_content_1');
	$header_content_2 = amazon_get_page('header_content_2');
	$footer_content = amazon_get_page('footer_content');
}

function amazon_update_page($key, $val) {
	global $db;
	$result = sqlite_query($db, "SELECT val FROM Page WHERE key='".$key."'", SQLITE_ASSOC);
	$line = sqlite_fetch_array($result);
	if( $line ) {
		sqlite_exec($db, "UPDATE Page SET val='".$val."' WHERE key='".$key."'");
	} else {
		sqlite_exec($db, "INSERT INTO Page(val, key) VALUES('".$val."', '".$key."')");
	}
}
//#################Page####################

//#####################cache####################
function scanDirectories($rootDir) {
    // set filenames invisible if you want
    $invisibleFileNames = array(".", "..", ".htaccess", ".htpasswd");
    // run through content of root directory
    $dirContent = scandir($rootDir);
    $allData = array();
    // file counter gets incremented for a better
    $fileCounter = 0;
    foreach($dirContent as $key => $content) {
        // filter all files not accessible
        $path = $rootDir.'/'.$content;
        if(!in_array($content, $invisibleFileNames)) {
            // if content is file & readable, add to array
            if(is_file($path) && is_readable($path)) {
                $tmpPathArray = explode("/",$path);
                // saving filename
                $allData['fileName'][$fileCounter] = end($tmpPathArray);
                // saving while path (for better access)
                $allData['filePath'][$fileCounter] = $path;
                // get file extension
                $filePartsTmp = explode(".", end($tmpPathArray));
                $allData['fileExt'][$fileCounter] = end($filePartsTmp);
                // get file date
                $allData['fileDate'][$fileCounter] = filectime($path);
				// get modifier date
                $allData['fileModifierDate'][$fileCounter] = filemtime($path);
                // get filesize in byte
                $allData['fileSize'][$fileCounter] = filesize($path);
                $fileCounter++;
            // if content is a directory and readable, add path and name
            }elseif(is_dir($path) && is_readable($path)) {
                $dirNameArray = explode('/',$path);
                $allData['dirPath'][$path] = $path;
                $allData['dirName'][$path] = end($dirNameArray);
                // recursive callback to open new directory
                $allData['content'][$path] = scanDirectories($path);
            }
        }
    }
    return $allData;
}

function php_createFolder($folder)
{
	if (!is_dir($folder))
	{
		mkdir($folder,0777,true) or die("cannot create folder");
		chmod($folder,0777);
	}
}

function php_unlink($folder)
{
	unlink($folder);
}

function php_deleteFolder($rootDir)
{
	$invisibleFileNames = array(".", "..", ".htaccess", ".htpasswd");
    // run through content of root directory
    $dirContent = scandir($rootDir);
    $allData = array();
    // file counter gets incremented for a better
    $fileCounter = 0;
    foreach($dirContent as $key => $content) 
	{
        // filter all files not accessible
        $path = $rootDir.'/'.$content;
        if(!in_array($content, $invisibleFileNames)) 
		{
			if(is_file($path) && is_readable($path)) 
				php_unlink($path);
		}
	}
	rmdir($rootDir);
}

function _reload($url)
{
	echo '<script language="javascript">
		location="'.$url.'";
	</script>';
	exit();
}//end function _reload
//#####################cache####################

//#####################contactus####################
function php_sendmail($fromMail,$fromName,$subject,$message)
{
	global  $systemMailEmail,$systemMailPassword,$smtpEmail,$smtpPort,$contactName,$contactEmail;
	$toName = $contactName;
	$toMail = $contactEmail;
	require_once('PHPMailer_v5.1/class.phpmailer.php');
	$mail = new PHPMailer();
	$mail->CharSet = "utf-8";
	$mail->IsSMTP(); // telling the class to use SMTP
	$mail->SMTPDebug  = 1;                     // enables SMTP debug information (for testing)
											   // 1 = errors and messages
											   // 2 = messages only
	$mail->SMTPAuth   = true;                  // enable SMTP authentication
	$mail->Host       = $smtpEmail; // sets the SMTP server
	$mail->Port       = $smtpPort;                    // set the SMTP port for the GMAIL server
	$mail->Username   = $systemMailEmail; // SMTP account username
	$mail->Password   = $systemMailPassword;        // SMTP account password
	$mail->SetFrom($fromMail, $fromName);
	$mail->Subject    = $subject;
	$mail->AltBody    = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
	$mail->MsgHTML($message);
	$mail->AddAddress($toMail, $toName);
	return $mail->Send();
}
//#####################contactus####################

//#######################other################################
function php_replaceContent($strContent)
{
	global $home_title,$home_url,$keyword_1,$keyword_2,$title;
	$website = "<a href='".$home_url."'>".$home_title."</a>";
	$arrkey = array("[HOMETITLE]", "[HOMEURL]", "[PRODUCT]", "[KEYWORD]", "[KEYWORD2]","[WEBSITE]");
	$arrval   = array($home_title, $home_url,$title,$keyword_1,$keyword_2,$website);
	$showContent = str_replace($arrkey, $arrval, $strContent);
	return $showContent;
}
//#######################other################################


//#######################searc_engine#########################
function pk_stt2_function_get_referer() {
    if (!isset($_SERVER['HTTP_REFERER']) || ($_SERVER['HTTP_REFERER'] == '')) return false;
    $referer_info = parse_url($_SERVER['HTTP_REFERER']);
    $referer = $referer_info['host'];
    if(substr($referer, 0, 4) == 'www.')
        $referer = substr($referer, 4);
    return $referer;
}

function pk_stt2_function_get_delimiter($ref) {
    $search_engines = array('google.com' => 'q',
			'go.google.com' => 'q',
			'images.google.com' => 'q',
			'video.google.com' => 'q',
			'news.google.com' => 'q',
			'blogsearch.google.com' => 'q',
			'maps.google.com' => 'q',
			'local.google.com' => 'q',
			'search.yahoo.com' => 'p',
			'search.msn.com' => 'q',
			'bing.com' => 'q',
			'msxml.excite.com' => 'qkw',
			'search.lycos.com' => 'query',
			'alltheweb.com' => 'q',
			'search.aol.com' => 'query',
			'search.iwon.com' => 'searchfor',
			'ask.com' => 'q',
			'ask.co.uk' => 'ask',
			'search.cometsystems.com' => 'qry',
			'hotbot.com' => 'query',
			'overture.com' => 'Keywords',
			'metacrawler.com' => 'qkw',
			'search.netscape.com' => 'query',
			'looksmart.com' => 'key',
			'dpxml.webcrawler.com' => 'qkw',
			'search.earthlink.net' => 'q',
			'search.viewpoint.com' => 'k',
			'mamma.com' => 'query');
    $delim = false;
    if (isset($search_engines[$ref])) {
        $delim = $search_engines[$ref];
    } else {
        if (strpos('ref:'.$ref,'google'))
            $delim = "q";
		elseif (strpos('ref:'.$ref,'search.atomz.'))
            $delim = "sp-q";
		elseif (strpos('ref:'.$ref,'search.msn.'))
            $delim = "q";
		elseif (strpos('ref:'.$ref,'search.yahoo.'))
            $delim = "p";
        elseif (preg_match('/home\.bellsouth\.net\/s\/s\.dll/i', $ref))
            $delim = "bellsouth";
    }
    return $delim;
}

function pk_stt2_function_get_terms($d) {
    $terms       = null;
    $query_array = array();
    $query_terms = null;
    $query = explode($d.'=', $_SERVER['HTTP_REFERER']);
    $query = explode('&', $query[1]);
    $query = urldecode($query[0]);
    $query = str_replace("'", '', $query);
    $query = str_replace('"', '', $query);
    $query_array = preg_split('/[\s,\+\.]+/',$query);
    $query_terms = implode(' ', $query_array);
    $terms = htmlspecialchars(urldecode(trim($query_terms)));
    return $terms;
}

function pk_stt2_is_contain_process($keyword){
	global $db;
	$meta_link = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	
	if ($keyword!="" && $meta_link!="")
	{
		$result = sqlite_query($db, "SELECT meta_count FROM search_engine WHERE meta_value='".$keyword."' and meta_link='".$meta_link."'", SQLITE_ASSOC);
		$count = sqlite_fetch_array($result);
		if( $count["meta_count"]>0 ) {
			$meta_count = $count["meta_count"]+1;
			sqlite_exec($db, "UPDATE search_engine SET meta_count='".$meta_count."',meta_link='".$meta_link."',last_modified='".time()."' WHERE meta_value='".$keyword."' and meta_link='".$meta_link."'");
		} else {
			sqlite_exec($db, "INSERT INTO search_engine(meta_value, meta_count,meta_link,last_modified) VALUES('".$keyword."','1','".$meta_link."','".time()."')");
		}
	}
}

function pk_stt2_function_createTable(){
	global $db;
	$sql = "SELECT id as countid FROM search_engine";
	$result = sqlite_query($db, $sql, SQLITE_ASSOC, $query_error);
	if($query_error){  
		sqlite_exec($db, "CREATE TABLE [search_engine] (
							[id] INTEGER  PRIMARY KEY NOT NULL,
							[meta_value] VARCHAR(255)  NULL,
							[meta_count] INTEGER  NULL,
							[meta_link] VARCHAR(255)  NULL,
							[last_modified] TIMESTAMP NULL
						);");
	}
}

function pk_stt2_function_wp_head_hook() {

		pk_stt2_function_createTable();	
		$referer = pk_stt2_function_get_referer();
		//echo $referer."<br>";
		if (!$referer) return false;
		$delimiter = pk_stt2_function_get_delimiter($referer);
		//echo $delimiter."<br>";
		if( $delimiter ){
			$term = pk_stt2_function_get_terms($delimiter);		
			//echo $term;
			$search_keyword = pk_stt2_is_contain_process( $term );
			pk_stt2_function_show_data();
		}
}

function pk_stt2_function_show_data(){
	global $arr_popular_search_engine,$arr_random_search_engine,$arr_last_search_engine,$db,$xConfig;
	/*unset($arr_popular_search_engine);
	unset($arr_random_search_engine);
	unset($arr_last_search_engine);
	$arr_popular_search_engine = array();
	$arr_random_search_engine = array();
	$arr_last_search_engine = array();*/
	$result = sqlite_query($db, "SELECT meta_value,meta_link FROM search_engine order by meta_count DESC,last_modified DESC limit 0,".$xConfig["size_popular_search"], SQLITE_ASSOC);
	while ($row = sqlite_fetch_array($result))
	{
		$arr_popular_search_engine[$row["meta_value"]] = $row["meta_link"];
		$index++;
	}
	
	$result = sqlite_query($db, "SELECT meta_value,meta_link FROM search_engine order by random() limit 0,".$xConfig["size_random_search"], SQLITE_ASSOC);
	$index=0;
	while ($row = sqlite_fetch_array($result))
	{
		$arr_random_search_engine[$row["meta_value"]] = $row["meta_link"];
		$index++;
	}
	
	$result = sqlite_query($db, "SELECT meta_value,meta_link FROM search_engine order by last_modified DESC limit 0,".$xConfig["size_last_search"], SQLITE_ASSOC);
	$index=0;
	while ($row = sqlite_fetch_array($result))
	{
		$arr_last_search_engine[$row["meta_value"]] = $row["meta_link"];
		$index++;
	}
}

function pk_stt2_function_show_data_admin(){
	global $arr_engine_id,$arr_engine_meta_value,$arr_engine_meta_count,$arr_engine_meta_link,$arr_engine_last_modified,$db;
	pk_stt2_function_createTable();
	$result = sqlite_query($db, "SELECT * FROM search_engine order by meta_count DESC,last_modified DESC", SQLITE_ASSOC);
	$index=0;
	while ($row = sqlite_fetch_array($result))
	{
		$arr_engine_id[$index] = $row["id"];
		$arr_engine_meta_value[$index] = $row["meta_value"];
		$arr_engine_meta_count[$index] = $row["meta_count"];
		$arr_engine_meta_link[$index] = $row["meta_link"];
		$arr_engine_last_modified[$index] = $row["last_modified"];
		$index++;
	}
}


function amazon_tag_description(){
	global $db;
	$meta_link = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	
	$index = 0;
	$result = sqlite_query($db, "SELECT meta_value FROM search_engine WHERE meta_link='".$meta_link."'", SQLITE_ASSOC);
	while ($row = sqlite_fetch_array($result))
	{
		$arr_detail_description[$index] = $row["meta_value"];
		$index++;
	}
	return $arr_detail_description;
}
//#######################searc_engine#########################


//#########################go to website######################
function go_to_url($url)
{
	//echo $url;
	//echo "test";
	echo "<script language='javascript'>
		location='".$url."'
	</script>";
}
//#########################go to website######################

//#######################################edit by bird###########################################

?>